import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from "@/views/Login.vue"
import Layout from "@/views/Layout.vue"
import TestPaper from "@/views/TestPaper.vue"
import QuestionBank from "@/views/QuestionBank.vue"
import TestRecord from "@/views/TestRecord.vue"
import store from "../store/index"

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "/",
    component: Layout,
    redirect: "/testrecord",
    children: [
      {
        path: "/questionbank",
        name: "题库",
        component: QuestionBank
      },
      {
        path: "/testrecord",
        name: "考试记录",
        component: TestRecord
      },
      {
        path: "/paper/:id",
        component: TestRecord
      },
      {
        path: "/grade/:id",
        component: TestRecord
      },
    ],
    meta: {
      requiresAuth: true
    }
  },
  {
    path: "/testpaper",
    name: "TestPaper",
    component: TestPaper,
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((route, redirect, next) => {
  const loginUser = store.state.loginUser
  if (route.matched.some(r => r.meta.requiresAuth) && loginUser === 0) {
    next({
      path: '/login',
      query: {
        redirect: route.fullPath
      }
    })
  } else {
    next()
  }
})
export default router
